/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaPrincipal.java
 *
 * Created on May 31, 2011, 11:24:44 AM
 */
package funcenter.gui;

import funcenter.db.Conexao;
import funcenter.main.Configuracoes;
import funcenter.main.Main;
import funcenter.main.Unzipper;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author arthur
 */
public class JanelaPrincipal extends javax.swing.JFrame {

    PainelDescricao[] paineisDescricao;
    Configuracoes[] configJogos;
    
    /** Creates new form JanelaPrincipal */
    public JanelaPrincipal() {
        initComponents();
        
        this.carregarJogos();
        botaoFecharDescricao.setVisible(false);
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        barraSuperior = new javax.swing.JToolBar();
        botaoAdicionarJogo = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        botaoTrocarJogo = new javax.swing.JButton();
        botaoNovaPartida = new javax.swing.JButton();
        botaoRanking = new javax.swing.JButton();
        painelSeparacao = new javax.swing.JSplitPane();
        divisaoDescricao = new javax.swing.JSplitPane();
        painelSuperiorDescricao = new javax.swing.JPanel();
        labelTitulo = new javax.swing.JLabel();
        botaoFecharDescricao = new javax.swing.JButton();
        painelDescricao = new funcenter.gui.PainelDescricao();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Fun Center");
        setMinimumSize(new java.awt.Dimension(750, 450));

        barraSuperior.setRollover(true);

        botaoAdicionarJogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/funcenter/images/list-add.png"))); // NOI18N
        botaoAdicionarJogo.setText("Adicionar");
        botaoAdicionarJogo.setFocusable(false);
        botaoAdicionarJogo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoAdicionar(evt);
            }
        });
        barraSuperior.add(botaoAdicionarJogo);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/funcenter/images/list-remove.png"))); // NOI18N
        jButton1.setText("Remover");
        jButton1.setFocusable(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoRemover(evt);
            }
        });
        barraSuperior.add(jButton1);

        botaoTrocarJogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/funcenter/images/ranking.png"))); // NOI18N
        botaoTrocarJogo.setText("Ranking");
        botaoTrocarJogo.setFocusable(false);
        barraSuperior.add(botaoTrocarJogo);

        botaoNovaPartida.setIcon(new javax.swing.ImageIcon(getClass().getResource("/funcenter/images/logout.png"))); // NOI18N
        botaoNovaPartida.setText("Logout");
        botaoNovaPartida.setFocusable(false);
        botaoNovaPartida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoLogout(evt);
            }
        });
        barraSuperior.add(botaoNovaPartida);

        botaoRanking.setIcon(new javax.swing.ImageIcon(getClass().getResource("/funcenter/images/sair.png"))); // NOI18N
        botaoRanking.setText("Sair");
        botaoRanking.setFocusable(false);
        botaoRanking.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoSair(evt);
            }
        });
        barraSuperior.add(botaoRanking);

        getContentPane().add(barraSuperior, java.awt.BorderLayout.PAGE_START);

        painelSeparacao.setDividerLocation(200);
        painelSeparacao.setDividerSize(2);
        painelSeparacao.setMinimumSize(new java.awt.Dimension(550, 370));

        divisaoDescricao.setDividerSize(0);
        divisaoDescricao.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        painelSuperiorDescricao.setLayout(new java.awt.BorderLayout());

        labelTitulo.setFont(new java.awt.Font("Dialog", 1, 18));
        labelTitulo.setText("Fun Center");
        labelTitulo.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 20, 5, 5));
        painelSuperiorDescricao.add(labelTitulo, java.awt.BorderLayout.LINE_START);

        botaoFecharDescricao.setText("X");
        botaoFecharDescricao.setMargin(new java.awt.Insets(2, 2, 2, 2));
        botaoFecharDescricao.setPreferredSize(new java.awt.Dimension(30, 10));
        botaoFecharDescricao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clicarBotaoFechar(evt);
            }
        });
        painelSuperiorDescricao.add(botaoFecharDescricao, java.awt.BorderLayout.LINE_END);

        divisaoDescricao.setTopComponent(painelSuperiorDescricao);
        divisaoDescricao.setRightComponent(painelDescricao);

        painelSeparacao.setRightComponent(divisaoDescricao);

        getContentPane().add(painelSeparacao, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clicarBotaoFechar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoFechar
        divisaoDescricao.setRightComponent(this.painelDescricao);
        labelTitulo.setText("Fun Center");
        botaoFecharDescricao.setVisible(false);
    }//GEN-LAST:event_clicarBotaoFechar

    private void clicarBotaoSair(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoSair
        int resp = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja sair?", "Sair", JOptionPane.YES_NO_OPTION);

        if(resp == JOptionPane.YES_OPTION){            
            try {
                Conexao.getInstance().fechar();
            } catch(Exception ex){
                Logger.getLogger(JanelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.exit(0);
        }
    }//GEN-LAST:event_clicarBotaoSair

    private void clicarBotaoLogout(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoLogout
        int resp = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja fazer logout?", "Logout", JOptionPane.YES_NO_OPTION);

        if(resp == JOptionPane.YES_OPTION){
            this.dispose();
            Main.log();
        }
    }//GEN-LAST:event_clicarBotaoLogout

    private void clicarBotaoAdicionar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoAdicionar
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".zip")
                        || f.isDirectory();
            }
            @Override
            public String getDescription() {
                return "ZIP Files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if(r == JFileChooser.APPROVE_OPTION){
            String zipname = chooser.getSelectedFile().getPath();
            Unzipper.unzip(zipname, "./jogos/");
            JOptionPane.showMessageDialog(this, "Jogo adicionado com sucesso!");
            this.carregarJogos();            
        }
    }//GEN-LAST:event_clicarBotaoAdicionar

    private void clicarBotaoRemover(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clicarBotaoRemover
        String[] jogos = new String[configJogos.length];
        for(int i = 0; i < configJogos.length; i++){
            jogos[i] = configJogos[i].getNomeJogo();
        }
        
        File dir = new File("./jogos/");
        File[] pastas = dir.listFiles();
        JanelaExcluirJogo janela = new JanelaExcluirJogo(this, true, jogos, pastas);
        janela.setVisible(true);
    }//GEN-LAST:event_clicarBotaoRemover

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JanelaPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToolBar barraSuperior;
    private javax.swing.JButton botaoAdicionarJogo;
    private javax.swing.JButton botaoFecharDescricao;
    private javax.swing.JButton botaoNovaPartida;
    private javax.swing.JButton botaoRanking;
    private javax.swing.JButton botaoTrocarJogo;
    private javax.swing.JSplitPane divisaoDescricao;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel labelTitulo;
    private funcenter.gui.PainelDescricao painelDescricao;
    private javax.swing.JSplitPane painelSeparacao;
    private javax.swing.JPanel painelSuperiorDescricao;
    // End of variables declaration//GEN-END:variables

    private void adicionar(Configuracoes config, String linhaConfig){
        String[] cfg = linhaConfig.split("=");
        
        if(cfg[0].equals("nome")){
            config.setNomeJogo(cfg[1]);
        } else if(cfg[0].equals("descricao")){
            config.setDescricao(cfg[1]);
        } else if(cfg[0].equals("autor")){
            config.setAutor(cfg[1]);
        } else if(cfg[0].equals("data_versao")){
            String[] data = cfg[1].split("/");
            int dia = Integer.valueOf(data[0]);            
            int mes = Integer.valueOf(data[1]);
            int ano = Integer.valueOf(data[2]);
            GregorianCalendar dataVersao = new GregorianCalendar(dia, mes, ano);
            config.setDataVersao(dataVersao);
        } else if(cfg[0].equals("cmd_win")){
            config.setComandoWin(cfg[1]);
        } else if(cfg[0].equals("cmd_lin")){
            config.setComandoLin(cfg[1]);
        } else if(cfg[0].equals("cmd_mac")){
            config.setComandoMac(cfg[1]);
        } else if(cfg[0].equals("versao")){
            config.setVersao(cfg[1]);
        } else if(cfg[0].equals("ranking")){
            String[] colunasRanking = cfg[1].split("|");
            config.setColunasRanking(colunasRanking);
        }
    }
    
    public void trocarPainelDescricao(int index){
        divisaoDescricao.setRightComponent(this.paineisDescricao[index]);
        labelTitulo.setText(configJogos[index].getNomeJogo());
        botaoFecharDescricao.setVisible(true);
    }
    
    public final void carregarJogos(){
        File dir = new File("./jogos/");
        System.out.println(dir.getPath());
        
        configJogos = new Configuracoes[dir.listFiles().length];
        paineisDescricao = new PainelDescricao[dir.listFiles().length];
        
        for(int i = 0; i < dir.listFiles().length; i++){
            configJogos[i] = new Configuracoes();
            paineisDescricao[i] = new PainelDescricao();
            System.out.println(dir.listFiles()[i]);          
        
            try {
                FileReader reader = new FileReader(dir.listFiles()[i] + "/dados.txt");
                BufferedReader br = new BufferedReader(reader);
                String linha;
                try {
                    while((linha = br.readLine()) != null){
                        adicionar(configJogos[i], linha);
                    }
                } catch(IOException ex){
                    Logger.getLogger(PainelJogos.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                paineisDescricao[i].setDescricao(configJogos[i].getDescricao());
                paineisDescricao[i].setAutor(configJogos[i].getAutor());
                paineisDescricao[i].setVersao(configJogos[i].getVersao());
                SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                String data = dateFormat.format(configJogos[i].getDataVersao().getTime());
                paineisDescricao[i].setDataVersao(data);
            } catch(java.io.FileNotFoundException ex){
                File f = new File("dados.txt");
                try {
                    f.createNewFile();
                } catch(IOException ex1){
                    Logger.getLogger(PainelJogos.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }
        }
        
        PainelJogos painelJogos = new PainelJogos(configJogos);
        JPanel painelEsquerdo = new JPanel();
        painelEsquerdo.setLayout(new BorderLayout());
        painelEsquerdo.add(painelJogos, BorderLayout.NORTH);
        painelSeparacao.setLeftComponent(painelEsquerdo);               
        painelSeparacao.setDividerLocation(painelJogos.getMinimumSize().width);
    }
}
